package com.qdsgjsfk.vision.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseActivity;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.ui.dialog.AddStudentDialog;
import com.qdsgjsfk.vision.util.MatchUtil;
import com.qdsgjsfk.vision.util.NetUtil;
import com.rest.business.RestProxy;
import com.rest.response.BaseBooleanResponse;
import com.rest.response.BaseResponse;
import com.rest.response.ValidResponse;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 新增学生
 *
 * @time 2021/3/12 16:46
 */

public class AddStudentActivity extends BaseActivity {

    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.passport)
    EditText passport;
    @BindView(R.id.hometown)
    EditText hometown;
    @BindView(R.id.idcard)
    EditText idcard;
    @BindView(R.id.birth)
    TextView birth;
    @BindView(R.id.nation)
    EditText nation;
    @BindView(R.id.tv_class_name)
    TextView tv_class_name;
    @BindView(R.id.man)
    TextView man;
    @BindView(R.id.woman)
    TextView woman;
    @BindView(R.id.passport_container)
    LinearLayout sex_age_container;
    @BindView(R.id.btn_confirm)
    TextView btn_confirm;
    @BindView(R.id.rb_no_id_card)
    RadioButton rb_no_id_card;
    @BindView(R.id.no_id_card_container)
    LinearLayout no_id_card_container;
    @BindView(R.id.unChina)
    RadioButton unChina;
    @BindView(R.id.china)
    RadioButton china;
    @BindView(R.id.id_parent)
    LinearLayout id_parent;
    @BindView(R.id.passport_parent)
    LinearLayout passport_parent;
    @BindView(R.id.rb_id_card)
    RadioButton rbIdCard;
    @BindView(R.id.rg_id_card)
    RadioGroup rgIdCard;
    @BindView(R.id.stu_parent_name)
    EditText stuParentName;
    @BindView(R.id.stu_parent_phone)
    EditText stuParentPhone;
    @BindView(R.id.rb_school_in)
    RadioButton rbSchoolIn;
    @BindView(R.id.rb_school_out)
    RadioButton rbSchoolOut;
    @BindView(R.id.rb_school_no)
    RadioButton rbSchoolNo;
    @BindView(R.id.rg_hometown)
    RadioGroup rgHometown;
    @BindView(R.id.hometown_card)
    EditText hometownCard;

    String classId, taskId, classYear, orgId, sex = "男", schoolRoll = "10", code = "";
    int prefix;


    private AddStudentDialog mAddStudentDialog;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_add_student;
    }

    @Override
    protected void initViews() {
        idcard.setOnEditorActionListener( new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (MatchUtil.checkIDCard( idcard.getText().toString().trim(), mContext )) {
//                    birth.setText(idcard.getText().toString().substring(6, 14));
                }
                return false;
            }
        } );


        idcard.addTextChangedListener( new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (idcard.getText().toString().trim().length() == 18) {
                    if (MatchUtil.checkIDCard( idcard.getText().toString().trim(), mContext )) {
//                        birth.setText(idcard.getText().toString().substring(6, 14));
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        } );

        //有身份证权限
        if (BaseApplication.addChinaNoId) {
            no_id_card_container.setVisibility( View.VISIBLE );
        }
        if (BaseApplication.addUnChina) {
            unChina.setVisibility( View.VISIBLE );
        }

        //选了非大陆，切换成非大陆再切回来的时候，性别、出生日期显示
        unChina.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == true) {
                    id_parent.setVisibility( View.GONE );
                    //隐藏无身份证
                    no_id_card_container.setVisibility( View.GONE );
//                    checkbox_no_id_card.setChecked( false );
                    //显示性别和出生年月
                    sex_age_container.setVisibility( View.VISIBLE );
                    passport_parent.setVisibility( View.VISIBLE );
                }
            }
        } );
        //选择了大陆
        china.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == true) {
                    if (BaseApplication.addChinaNoId) {
                        no_id_card_container.setVisibility( View.VISIBLE );
                    }
                    passport_parent.setVisibility( View.GONE );

                    if (rb_no_id_card.isChecked()) {
                        idcard.setText( "" );
                        id_parent.setVisibility( View.GONE );
                        sex_age_container.setVisibility( View.VISIBLE );
                    } else {
                        sex_age_container.setVisibility( View.GONE );
                        id_parent.setVisibility( View.VISIBLE );
                    }
                }
            }
        } );

        rgIdCard.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_id_card:
                        //选择了有身份证
                        sex_age_container.setVisibility( View.GONE );
                        id_parent.setVisibility( View.VISIBLE );
                        break;
                    case R.id.rb_no_id_card:
                        //无身份证展示
                        idcard.setText( "" );
                        id_parent.setVisibility( View.GONE );
                        sex_age_container.setVisibility( View.VISIBLE );
                        break;
                    default:
                        break;
                }
            }
        } );

        rgHometown.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_school_in:
                        //学籍
                        schoolRoll = "10";
                        break;
                    case R.id.rb_school_out:
                        schoolRoll = "15";
                        break;
                    case R.id.rb_school_no:
                        schoolRoll = "20";
                        break;
                }
            }
        } );
    }

    @OnClick(R.id.birth)
    void birth() {
        InputMethodManager inputManager =
                (InputMethodManager) passport.getContext().getSystemService( Context.INPUT_METHOD_SERVICE );
        assert inputManager != null;
        inputManager.hideSoftInputFromWindow( passport.getWindowToken(), 0 );

        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set( 1970, 0, 1 );
        endDate.set( 2020, 11, 31 );

        TimePickerView pvTime = new TimePickerBuilder( this, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd" );
            String dateString = formatter.format( date );
            birth.setText( dateString );
        } ).setType( new boolean[]{true, true, true, false, false, false} )
                .setRangDate( startDate, endDate ).
                        build();
        pvTime.show();
    }

//    @OnClick(R.id.hometown)
//    void hometown(){
//        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
//                //返回的分别是三个级别的选中位置
//                String tx = options1Items.get(options1).getPickerViewText()
//                        + options2Items.get(options1).get(option2)
//                        + options3Items.get(options1).get(option2).get(options3).getPickerViewText();
//                tvOptions.setText(tx);
//            }
//        }).build();
//        pvOptions.setPicker(options1Items, options2Items, options3Items);
//        pvOptions.show();
//    }


    @Override
    protected void initData() {
        classId = getIntent().getStringExtra( "classId" );
        taskId = getIntent().getStringExtra( "taskId" );
        orgId = getIntent().getStringExtra( "orgId" );
        classYear = getIntent().getStringExtra( "classYear" );
        tv_class_name.setText( getIntent().getStringExtra( "gradeName" ) );
        prefix = getIntent().getIntExtra( "prefix", -1 );
    }

    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        valid();

    }

    @OnClick(R.id.passport)
    void passport() {
//        if(checkbox_passport.isChecked()){
//            return;
//        }
        passport.post( new Runnable() {
            @Override
            public void run() {
//                checkbox_passport.performClick();
                passport.setFocusable( true );
                passport.setFocusableInTouchMode( true );
                passport.requestFocus();
                passport.requestFocusFromTouch();
                idcard.setFocusable( false );
                idcard.setFocusableInTouchMode( false );
                InputMethodManager inputManager =
                        (InputMethodManager) passport.getContext().getSystemService( Context.INPUT_METHOD_SERVICE );
                assert inputManager != null;
                inputManager.showSoftInput( passport, 0 );
            }
        } );
    }

    @OnClick(R.id.idcard)
    void idcard() {
//        if(checkbox_id_card.isChecked()){
//            return;
//        }
        idcard.post( new Runnable() {
            @Override
            public void run() {
//                checkbox_id_card.performClick();
//                checkbox_no_id_card.setChecked( false );
                idcard.setFocusable( true );
                idcard.setFocusableInTouchMode( true );
                idcard.requestFocus();
                idcard.requestFocusFromTouch();
                passport.setFocusable( false );
                passport.setFocusableInTouchMode( false );
                InputMethodManager inputManager =
                        (InputMethodManager) passport.getContext().getSystemService( Context.INPUT_METHOD_SERVICE );
                assert inputManager != null;
                inputManager.showSoftInput( passport, 0 );
            }
        } );
    }


    /**
     * 新增学生
     *
     * @time 2020/5/21 11:24
     */
    private void uplaod() {
        if (TextUtils.isEmpty( name.getText().toString() )) {
            Toast.makeText( mContext, "请输入学生姓名", Toast.LENGTH_SHORT ).show();
            return;
        }

        String birth = "";
        String sex = "";

        if (china.isChecked()) {
            if (rb_no_id_card.isChecked()) {
                //选择了无身份证
                idcard.setText( "" );
                birth = this.birth.getText().toString().trim();
                sex = this.sex;
            } else {
                if (idcard.getText().toString().trim().length() != 18 || !MatchUtil.checkIDCard( idcard.getText().toString().trim(), mContext )) {
                    Toast.makeText( mContext, "请检查您的身份证号", Toast.LENGTH_SHORT ).show();
                    return;
                }
                String temp = idcard.getText().toString().substring( 6, 14 );
                birth = temp.substring( 0, 4 ) + "-" + temp.substring( 4, 6 ) + "-" + temp.substring( 6, 8 );
                if (Integer.parseInt( idcard.getText().toString().substring( 16, 17 ) ) % 2 == 0) {
                    sex = "女";
                } else {
                    sex = "男";
                }
            }
        } else {
            //非大陆
            birth = this.birth.getText().toString().trim();
            sex = this.sex;
        }
        String stuType = "";
        if (china.isChecked()) {
            if (rb_no_id_card.isChecked()) {
                stuType = "3";
            } else {
                stuType = "1";
            }

        } else {
            stuType = "2";
        }

        if (TextUtils.isEmpty( birth )) {
            Toast.makeText( mContext, "请填写出生日期", Toast.LENGTH_SHORT ).show();
            return;
        }
        if (unChina.isChecked()) {
            if (TextUtils.isEmpty( passport.getText().toString().trim() )) {
                Toast.makeText( mContext, "请填护照", Toast.LENGTH_SHORT ).show();
                return;
            }
        }

        //学籍号
        code = hometownCard.getText().toString().trim();
        showProgressDialog( mContext );
        RestProxy.getInstance().saveStudent( name.getText().toString(), hometown.getText().toString(), nation.getText().toString(), birth, sex, idcard.getText().toString(), passport.getText().toString(), orgId + "", classId + "", taskId, stuType, schoolRoll, code, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                dismissProgressDialog();
                Toast.makeText( mContext, "保存成功", Toast.LENGTH_SHORT ).show();
                finish();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                dismissProgressDialog();
                NetUtil.onError( e, mContext );
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    /**
     * 检查身份证号
     *
     * @time 2020/5/21 10:43
     */
    private void valid() {
        if (TextUtils.isEmpty( name.getText().toString() )) {
            Toast.makeText( mContext, "请输入学生姓名", Toast.LENGTH_SHORT ).show();
            return;
        }
        String birth = "";
        String sex = "";

        if (china.isChecked()) {
            if (rb_no_id_card.isChecked()) {//选择了无身份证
                idcard.setText( "" );
                birth = this.birth.getText().toString().trim();
                sex = this.sex;
            } else {
                if (idcard.getText().toString().trim().length() != 18 || !MatchUtil.checkIDCard( idcard.getText().toString().trim(), mContext )) {
                    Toast.makeText( mContext, "请检查您的身份证号", Toast.LENGTH_SHORT ).show();
                    return;
                }
                String temp = idcard.getText().toString().substring( 6, 14 );
                birth = temp.substring( 0, 4 ) + "-" + temp.substring( 4, 6 ) + "-" + temp.substring( 6, 8 );
                if (Integer.parseInt( idcard.getText().toString().substring( 16, 17 ) ) % 2 == 0) {
                    sex = "女";
                } else {
                    sex = "男";
                }
            }
        } else {
            birth = this.birth.getText().toString().trim();
            sex = this.sex;
        }
        String stuType = "";
        if (china.isChecked()) {
            if (rb_no_id_card.isChecked()) {
                stuType = "3";
            } else {
                stuType = "1";
            }

        } else {
            stuType = "2";
        }

        if (TextUtils.isEmpty( birth )) {
            Toast.makeText( mContext, "请填写出生日期", Toast.LENGTH_SHORT ).show();
            return;
        }
        Log.e( "classYear---", classYear );

        String finalSex = sex;
        String finalBirth = birth;
        String finalStuType = stuType;
        //检查任务是否有效，筛查计划是否完成
        RestProxy.getInstance().canOperateByPlanStatus( orgId + "", new Observer<BaseBooleanResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseBooleanResponse baseResponse) {
                try {
                    if (baseResponse.data) {//检查身份证是否被占用
                        RestProxy.getInstance().validStudent( prefix + "", orgId + "", name.getText().toString(), idcard.getText().toString(), finalSex, finalBirth, finalStuType, "0", classId + "", classYear, new Observer<ValidResponse>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(ValidResponse validResponse) {
                                if (validResponse.data != null) {
                                    if (validResponse.data.canChange == 1) {
                                        uplaod();
                                    } else {
                                        mAddStudentDialog = AddStudentDialog.newInstance( validResponse.data.errorMsg );
                                        mAddStudentDialog.show( getSupportFragmentManager(), "mAddStudentDialog" );
                                        mAddStudentDialog.setmListener( new AddStudentDialog.OnItemClickListener() {

                                            @Override
                                            public void onConfirm() {
                                                mAddStudentDialog.dismiss();
                                            }

                                            @Override
                                            public void onCancel() {
                                            }
                                        } );
                                    }
                                }

                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                                NetUtil.onError( e, mContext );
                            }

                            @Override
                            public void onComplete() {

                            }
                        } );

                    } else {
                        Toast.makeText( mContext, "请先打开当前选择的筛查任务，才能继续该操作", Toast.LENGTH_SHORT ).show();
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, mContext );
            }

            @Override
            public void onComplete() {

            }
        } );


    }


    @OnClick(R.id.man)
    void man() {
        man.setBackgroundResource( R.drawable.item_bg_blue_button );
        woman.setBackgroundResource( R.drawable.item_bg_grey_button );
        man.setTextColor( getResources().getColor( R.color.white ) );
        woman.setTextColor( getResources().getColor( R.color.commonBlack ) );
        sex = "男";
    }

    @OnClick(R.id.woman)
    void woman() {
        woman.setBackgroundResource( R.drawable.item_bg_blue_button );
        man.setBackgroundResource( R.drawable.item_bg_grey_button );
        woman.setTextColor( getResources().getColor( R.color.white ) );
        man.setTextColor( getResources().getColor( R.color.commonBlack ) );
        sex = "女";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        // TODO: add setContentView(...) invocation
        ButterKnife.bind( this );
    }
}
